import store from '@/store/index.js'

function isBlank(data) {
	return typeof data === 'undefined' || data == null || data.trim() === ""
}

function getnum(num = 0) {
	let aNew;
	let re = /([0-9]+\.[0-9]{2})[0-9]*/;
	aNew = num.toString().replace(re, "$1");
	return aNew
}
// 节流
function throttle(func, delay = 1000) {
	var prev = Date.now()
	return function() {
		var context = this;
		var args = arguments;
		var now = Date.now();
		if (now - prev >= delay) {
			func.apply(context, args);
			prev = Date.now();
		}
	}
}

//参数：func函数，delay延迟时间
function debounce(func, delay = 50) {
	let timer = null
	return function(...args) {
		if (timer) clearTimeout(timer)
		timer = setTimeout(() => {
			func.apply(this, args)
		}, delay)
	}
}
// 深克隆
function deepCopy(value) {
	if (value instanceof Function) return value
	else if (value instanceof Array) {
		var newValue = []
		for (let i = 0; i < value.length; ++i) newValue[i] = deepCopy(value[i])
		return newValue
	} else if (value instanceof Object) {
		var newValue = {}
		for (let i in value) newValue[i] = deepCopy(value[i])
		return newValue
	} else return value
}

function randomString(length) {
	var str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var result = '';
	for (var i = length; i > 0; --i)
		result += str[Math.floor(Math.random() * str.length)];
	return result;
}

function showToast(title = '', icon = 'none', duration = 500) {
	uni.showToast({
		title,
		icon,
		duration,
		position: 'center',
		mask: true
	});
}
// 判断TOKEN
function islogin() {
	let token = store.state.token || ''
	if (!token) {
		const {
			route
		} = getCurrentPages().pop();
		uni.setStorageSync("originRoute", route || 'pages/index/index');
		uni.reLaunch({
			url: '/pages/my/login/login'
		})
	}
}

function switchTabcart() {
	uni.switchTab({
		url: '/pages/cart/cart'
	})
}
export default {
	isBlank,
	debounce,
	deepCopy,
	islogin,
	showToast,
	getnum,
	throttle,
	randomString,
	switchTabcart,
	isUndefined(data) {
		return typeof(data) == 'undefined'
	},
	ispassword(data) {
		return data.length >= 6 && data.length <= 15
	},

}